package com.example.demo.service;

import com.example.demo.bean.UserInfo;
import com.example.demo.dao.UserMapper;
import com.example.demo.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpSession;
import java.util.Random;

@Service
public class MailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserMapper userMapper;//注入UserMapper
    //application.yml中已配置的值
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 随机生成6位数的验证码
     */
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 给前端输入的邮箱，发送验证码
     */
    public boolean sendMimeMail(String email) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
            String code = randomCode();

            //将随机数和邮箱存入redis
            redisUtils.set("emailcode",code);
            redisUtils.set("email",email);

            mailMessage.setText("您收到的验证码是：" + code);//内容

            mailMessage.setTo(email);//发给谁，收件人

            mailMessage.setFrom(from);//你自己的邮箱,发件人

            mailSender.send(mailMessage);//发送
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断验证码是否正确
     */
    public boolean CheckCode(UserInfo userInfo) {
        //获取redis中的验证信息
        String emailcode= (String) redisUtils.get("emailcode");
        String email = (String) redisUtils.get("email");

        //获取表单中的提交的验证信息
        String voCode = userInfo.getCode();
        //如果email数据为空，或者不一致，注册失败
        if (email == null || email.isEmpty()) {
            return false;
        } else if (!emailcode.equals(voCode)) {
            return false;
        }

        return true;
    }
}
